package com.marketingexpert.controller.marketingmgnt.autoMarketing;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.marketingexpert.domain.Trend;
import com.marketingexpert.domain.User;
import com.marketingexpert.exception.MarketingExpertException;
import com.marketingexpert.service.marketingmgnt.MarketingService;
import com.marketingexpert.service.usermgnt.UserService;
import com.marketingexpert.util.Resources;

public class LoadExistTrendController implements Controller {

	private static Logger logger = Logger.getLogger(LoadExistTrendController.class); 
	
	private UserService userService;
	
	private MarketingService marketingService;
	
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		response.setContentType("application/x-json;charset=GBK"); 
		response.setHeader("Pragma", "No-cache"); 
		response.setHeader("Cache-Control", "no-cache"); 
		response.setHeader("Cache-Control", "no-store"); 
		response.setDateHeader("Expires", 0);  
		
		PrintWriter out = response.getWriter();
		
		String parentUserId = (String) request.getSession().getAttribute("parentUserId");
		try {
			User user = getUserService().queryUserByUId(parentUserId);
			List<Trend> trends = getMarketingService().queryAllTrendByPId(user.getId());
			JSONArray jsonTrends = JSONArray.fromObject(trends);
			out.print(jsonTrends);
			return null; 
		} catch(MarketingExpertException e) {
			logger.error(Resources.getString("LoadExistTrendController.loadExistTrendError"), e);
			out.print(Resources.getString("LoadExistTrendController.loadExistTrendError"));
			return null;
		}
	}

	public MarketingService getMarketingService() {
		return marketingService;
	}

	public void setMarketingService(MarketingService marketingService) {
		this.marketingService = marketingService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
}
